package com.zbkj.common.utils;

import cn.hutool.core.img.ImgUtil;
import cn.hutool.http.HttpUtil;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.text.DecimalFormat;

/**
 * 通用工具类
 * +----------------------------------------------------------------------
 * | CRMEB [ CRMEB赋能开发者，助力企业发展 ]
 * +----------------------------------------------------------------------
 * | Copyright (c) 2016~2025 https://www.crmeb.com All rights reserved.
 * +----------------------------------------------------------------------
 * | Licensed CRMEB并不是自由软件，未经许可不能去掉CRMEB相关版权
 * +----------------------------------------------------------------------
 * | Author: CRMEB Team <admin@crmeb.com>
 * +----------------------------------------------------------------------
 */
public class PositionUtil {

    private static final double EARTH_RADIUS = 6371.0;

    /**
     *
     * @param lat1  纬度1
     * @param lon1  经度1
     * @param lat2  纬度2
     * @param lon2  经度2
     * @return
     */
    public static double calculateDistance(double lat1, double lon1, double lat2, double lon2) {
        double dLat = Math.toRadians(lat2 - lat1);
        double dLon = Math.toRadians(lon2 - lon1);
        double a = Math.sin(dLat / 2) * Math.sin(dLat / 2)
                + Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2))
                * Math.sin(dLon / 2) * Math.sin(dLon / 2);
        double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
        return EARTH_RADIUS * c;
    }


    public static String calculateDistance(String wjd1, String wjd2) throws Exception {
        if(!StringUtils.hasLength(wjd1) || !StringUtils.hasLength(wjd1)){
            throw new Exception("对比经纬度数据不准许为空！");
        }
        String[] s1 = wjd1.split(",");
        String[] s2 = wjd2.split(",");

        double lat1 = Double.valueOf(s1[0]);
        double lon1 = Double.valueOf(s1[1]);
        double lat2 = Double.valueOf(s2[0]);
        double lon2 = Double.valueOf(s2[1]);

        double dLat = Math.toRadians(lat2 - lat1);
        double dLon = Math.toRadians(lon2 - lon1);
        double a = Math.sin(dLat / 2) * Math.sin(dLat / 2)
                + Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2))
                * Math.sin(dLon / 2) * Math.sin(dLon / 2);
        double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
        double d = EARTH_RADIUS * c;
        DecimalFormat df = new DecimalFormat("0.00");
        return df.format(d);
    }



//
//    public static String getDistance(String wjd1, String wjd2) throws Exception {
//        if(!StringUtils.hasLength(wjd1) || !StringUtils.hasLength(wjd1)){
//            throw new Exception("对比经纬度数据不准许为空！");
//        }
//        String[] s1 = wjd1.split(",");
//        String[] s2 = wjd2.split(",");
//
//        // 定义两个经纬度点（纬度在前，经度在后）
//        Point point1 = new Point(31.2304, 121.4737);  // 上海
//        Point point2 = new Point(39.9042, 116.4074);  // 北京
//
//        // 计算球面距离（单位：米）
//        double distance = GisUtil.getDistance(point1, point2);
//        System.out.println("上海到北京的球面距离：" + distance + " 米");
//
//        // 计算平面距离（单位：米）
//        double planarDistance = GisUtil.getPlanarDistance(point1, point2);
//        System.out.println("上海到北京的平面距离：" + planarDistance + " 米");
//    }

//
//
//    public static void main(String[] args) {
//        String personUrl = "https://example.com/person.png";
//        String backgroundUrl = "https://example.com/background.jpg";
//        String outputPath = "hutool_composite.png";
//
//        // 1. 下载并读取图片
//        Image background = ImgUtil.read(HttpUtil.downloadBytes(backgroundUrl));
//        Image person = ImgUtil.read(HttpUtil.downloadBytes(personUrl));
//
//        // 2. 居中叠加人物
//        ImgUtil.pressImage(new File(outputPath), background, person, new Rectangle(
//                        (background.getWidth(null) - person.getWidth(null)) / 2,
//                        (background.getHeight(null) - person.getHeight(null)) / 2,
//                        person.getWidth(null),
//                        person.getHeight(null)),
// 1.0f // 透明度
//        );
//    }




    public static void main(String[] args) {
        // 远程图片 URL

//        String backgroundUrl = "https://image.yigouxuan.com/crmebimage/public/product/2025/05/26/33225e2c7dca4c5eb8f301d4dbeef7167efxrs3zzh.png";
        String backgroundUrl = "https://image.yigouxuan.com/crmebimage/public/content/2025/05/26/3f39809dad614a2c867fc416dc10ace1eu1uf6iu9t.png";
        String overlayUrl = "https://image.yigouxuan.com/crmebimage/public/product/2025/05/26/33225e2c7dca4c5eb8f301d4dbeef7167efxrs3zzh.png";

        try {
            // 1. 下载远程图片并转换为 BufferedImage
            BufferedImage background = downloadImage(backgroundUrl);
            BufferedImage overlay = downloadImage(overlayUrl);

            int x = (background.getWidth() - overlay.getWidth()) / 2;
            int y = (background.getHeight() - overlay.getHeight()) / 2;
            // 2. 叠加图片（覆盖到背景图的左上角）
            BufferedImage combined = overlayImages(background, overlay, x, y);

            // 3. 保存结果
            ImgUtil.write(combined, new File("result.jpg"));
            System.out.println("图片叠加完成！");
        } catch (IOException e) {
            System.err.println("处理失败: " + e.getMessage());
        }
    }

    /**
     * 从 URL 下载图片并转换为 BufferedImage
     */
    private static BufferedImage downloadImage(String imageUrl) throws IOException {
        // 使用 Hutool 的 HttpUtil 下载图片字节流
        byte[] imageBytes = HttpUtil.downloadBytes(imageUrl);
        return ImgUtil.read(new ByteArrayInputStream(imageBytes));
    }

    /**
     * 将 overlay 图片叠加到 background 的指定位置
     * @param background 背景图
     * @param overlay    叠加图
     * @param x          叠加位置 X 坐标
     * @param y          叠加位置 Y 坐标
     */
    private static BufferedImage overlayImages(BufferedImage background, BufferedImage overlay, int x, int y) {

        int width = Math.max(background.getWidth(), overlay.getWidth());
        int height = Math.max(background.getHeight(), overlay.getHeight());
        // 创建背景图的副本，避免修改原始图片
        BufferedImage combined = new BufferedImage(
                background.getWidth(),
                background.getHeight(),
                BufferedImage.TYPE_INT_ARGB // 支持透明度
        );

        Graphics2D g = combined.createGraphics();
        try {
            // 绘制背景图
            g.drawImage(background, 0, 0, null);
            // 设置前景图绘制位置（可以根据需求调整）
            int offsetX = (width - overlay.getWidth()) / 2;
            int offsetY = (height - overlay.getHeight()) / 2;

            // 绘制叠加图（带透明度）
            g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1.0f)); // 设置透明度（1.0 为不透明）
            g.drawImage(overlay, 0, 0, null);
        } finally {
            g.dispose();
        }
        return combined;
    }
}
